import {
  CanActivate,
  ExecutionContext,
  Inject,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Observable } from 'rxjs';
import { Role } from './user/entities/role.entity';
import { Request } from 'express';
import { Reflector } from '@nestjs/core';

declare module 'express' {
  export interface Request {
    user: {
      id: number;
      username: string;
      roles: Role[];
    };
  }
}

@Injectable()
export class LoginGuard implements CanActivate {
  @Inject(JwtService)
  private jwtService: JwtService;

  @Inject(Reflector)
  private reflector: Reflector;

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const requireLogin = this.reflector.getAllAndOverride<boolean>(
      'requireLogin',
      [context.getHandler(), context.getClass()],
    );
    if (!requireLogin) return true;

    console.log('需要登录', requireLogin);

    const request: Request = context.switchToHttp().getRequest();

    const authorization: string = request.headers['authorization'];
    console.log(authorization);

    const bearer: string[] = authorization?.split(' ');

    if (!bearer || bearer.length < 2) {
      throw new UnauthorizedException('无效 token');
    }

    try {
      const token: string = bearer.pop();
      const payload = this.jwtService.verify(token);
      request.user = payload.user;
      return true;
    } catch (error) {
      console.log(error);
      throw new UnauthorizedException('token 失效，请重新登录');
    }
  }
}
